<template>
  <div class="list_container flex both-100">
    <Breadcrumb :title="pageTitle" />
    <div class="content_container">
      <el-form ref="searchMap" class="serach_wrapper flex-space-between" :inline="true" :model="searchMap" @submit.native.prevent>
        <div class="search">
          <el-form-item prop="keyword" size="small">
            <el-select v-model="searchMap.questionType">
              <el-option v-for="dict in dict.type.exam_question_type" :key="dict.value" :label="dict.label" :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="keyword" size="small">
            <el-input v-model="searchMap.keyword" placeholder="请输入题目内容/题目选项" clearable @clear="handleSearch()" @keyup.enter.native="handleSearch" />
          </el-form-item>
          <el-form-item class="flex">
            <el-button @click="handleSearch()" class="btn_primary">查询</el-button>
            <el-button @click="handleReset()" class="btn_cancel">重置</el-button>
          </el-form-item>
        </div>
        <div class="edit flex">
          <!-- <el-button icon="el-icon-plus" class="btn_primary" @click="handleAdd()">
            批量导入
          </el-button> -->
          <el-button icon="el-icon-plus" class="btn_primary" @click="handleAdd()">
            新增
          </el-button>
        </div>
      </el-form>
      <div class="table_container">
        <el-table stripe v-loading="examMaterialLoading" :data="examQuestionList">
          <el-table-column type="index" label="序号" header-align="center" align="center" width="80"></el-table-column>
          <el-table-column prop="questionType" label="题型" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.exam_question_type" :value="scope.row.questionType" />
            </template>
          </el-table-column>
          <el-table-column prop="examQuestionContent" label="题目" align="center"></el-table-column>
          <el-table-column prop="questionItemInfo" label="选项" align="center">
            <template slot-scope="scope">
              {{ combineString(scope.row.questionItemInfo) }}
            </template>
          </el-table-column>
          <el-table-column prop="answer" label="答案" align="center"></el-table-column>
          <el-table-column label="操作" width="300" align="center">
            <template slot-scope="scope">
              <span type="text" class="tag_primary" size="small" @click="handleDetails(scope.row)">编辑</span>
              <span type="text" class="tag_warning" size="small" @click="handleDelete(scope.row)">删除</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination v-if="total>0" :total="total" :page.sync="searchMap.pageNum" :limit.sync="searchMap.pageSize" @change="getExamQuestionList" />
    </div>
    <el-dialog title="题库管理" class="m_dialog" :visible.sync="dialogVisableExamQuestion" :close-on-click-modal="false">
      <el-form ref="form" :model="formData" :rules="rules" label-width="120px" size="small">
        <el-form-item label="题型:" prop="questionType">
          <el-select v-model="formData.questionType">
            <el-option v-for="dict in dict.type.exam_question_type" :key="dict.value" :label="dict.label" :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题目:" prop="examQuestionContent">
          <el-input v-model="formData.examQuestionContent" />
        </el-form-item>
        <el-form-item label="选项:" prop="questionItemInfo">
          <span slot="label">
            <el-tooltip content="请输入答案并用 ‘ 空格 ’ 隔开，如：A.苹果,B.菠萝" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            选项:
          </span>
          <el-input v-model="formData.questionItemInfo" />
        </el-form-item>
        <el-form-item label="正确答案:" prop="answer">
          <el-input v-model="formData.answer" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisableExamQuestion = false" class="btn_cancel">取 消</el-button>
        <el-button @click="submitForm" type="primary" class="btn_primary">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExamQuestion, addExamQuestion, updateExamQuestion, getExamQuestionById, deleteExamQuestion } from '@/api/examination'
import UploadDrag from '@/components/UploadFiles'
export default {
  dicts: ['exam_question_type'],
  data () {
    return {
      // 搜索数据
      searchMap: {
        pageNum: 1, // 当前页
        pageSize: 10,  // 默认条数 
        keyword: undefined,
        questionType: undefined
      },
      // 考试资料数据
      formData: {},
      // 访客预约表单验证
      examQuestionRules: {
        examMaterialName: [{ required: true, message: '请输入材料名称', trigger: 'blur' }],
      },
      // 考试资料数据加载状态
      examQuestionLoading: false,
      // 条数
      total: 0,
      // 考试题库弹框
      dialogVisableExamQuestion: false,
      // 标题
      title: '',
      // 考试数据列表数据
      examQuestionList: [],
      // 表单验证
      rules: {
        examQuestionContent: [
          { required: true, message: '请输入题目', trigger: 'blur' },
        ],
        answer: [
          { required: true, message: '请输入答案', trigger: 'blur' }
        ],
        questionType: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
      }
    };
  },
  created () {
    this.getExamQuestionList();
  },
  computed: {
    pageTitle () {
      return '题库管理'
    }
  },
  watch: {},
  methods: {
    // 数组转字符串
    combineString (arr) {
      const answerItem = arr.map(item => `${item.itemName}: ${item.itemValue}`)
      const result = answerItem.join(' ')
      return result
    },
    getExamQuestionList () {
      this.examMaterialLoading = true;
      listExamQuestion(this.searchMap).then(res => {
        if (200 === res.code) {
          this.examQuestionList = res.rows
          this.total = res.total
          this.examMaterialLoading = false
        }
      })
    },
    // 点击资料详情
    handleDetails (row) {
      const examQuestionId = row.examQuestionId
      getExamQuestionById(examQuestionId).then(res => {
        if (res.code === 200) {
          this.formData = res.data
          this.formData.questionItemInfo = this.combineString(this.formData.questionItemInfo)
          this.dialogVisableExamQuestion = true
        }
      })
    },
    // 点击删除
    handleDelete (row) {
      console.log(row)
      const examQuestionId = [row.examQuestionId]
      this.$confirm('是否删除该题库').then(res => {
        return deleteExamQuestion(examQuestionId)
      }).then(() => {
        this.getExamQuestionList()
        this.$message.success('删除成功')
      })
    },
    // 点击新增考试资料
    handleAdd () {
      this.reset();
      this.formData.questionItemInfo = this.combineString(this.formData.questionItemInfo)
      this.dialogVisableExamQuestion = true
    },
    reset () {
      this.formData = {
        answer: '', // 答案
        examQuestionContent: '', // 内容
        questionItemInfo: [], // 选项信息
        questionType: "0" // 题目类型
      }
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    // 提交
    submitForm () {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          try {
            const isOperation = this.formData.examQuestionId === undefined
            let method = isOperation ? addExamQuestion : updateExamQuestion
            let message = isOperation ? '新增成功' : '修改成功'
            const params = {
              ...this.formData,
              questionItemInfo: this.sliceQuestionInfo(this.formData.questionItemInfo)
            }
            console.log(this.formData.questionItemInfo)
            const response = await method(params)
            if (response.code === 200) {
              this.$message.success(message)
              this.getExamQuestionList()
              this.dialogVisableExamQuestion = false
            }
          } catch (error) {
            this.$message.error('操作失败')
          }
        }
      })
    },
    // 字符串分割成数组
    sliceQuestionInfo (str) {
      const questionItem = str.split(' ')
      const result = []
      questionItem.forEach(item => {
        const parts = item.trim().split('.')
        if (parts.length === 2) {
          result.push({
            itemName: parts[0].trim(),
            itemValue: parts[1].trim()
          })
        }
      })
      return result
    },
    handleSearch () {
      this.getExamQuestionList()
    },
    handleReset () {
      this.searchMap = {
        pageNum: 1, // 当前页
        pageSize: 10,  // 默认条数 
        keyword: undefined,
      }
      this.getExamQuestionList()
    }
  },
  components: {
    UploadDrag
  }
}
</script>
<style lang='less' scoped>
</style>